package api

import (
	"net/http"
	"strconv"

	"erp/config"
	"erp/logic"
	"erp/model"
	"erp/util"

	"github.com/gin-gonic/gin"
)

func RegisterOrderRoutes(r *gin.Engine) {
	s := logic.OrderService{DB: config.DB}

	// 创建订单
	r.POST("/orders", func(c *gin.Context) {
		var o model.Order
		if err := c.ShouldBindJSON(&o); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		if err := s.CreateOrder(&o); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, o)
	})

	// 分页查询订单（支持按客户名查询）
	r.GET("/orders", func(c *gin.Context) {
		p := util.GetPage(c)
		var list []model.Order
		q := config.DB.Model(&model.Order{})
		if kw := c.Query("customer"); kw != "" {
			q = q.Where("customer LIKE ?", "%"+kw+"%")
		}
		if status := c.Query("status"); status != "" {
			q = q.Where("status = ?", status)
		}
		if warehouse := c.Query("warehouse"); warehouse != "" {
			q = q.Where("warehouse = ?", warehouse)
		}
		var total int64
		q.Count(&total)
		if err := q.Preload("Items").Offset(p.Offset).Limit(p.Limit).Order("id DESC").Find(&list).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"items": list, "total": total, "page": p.Page, "pageSize": p.PageSize})
	})

	// 获取订单详情
	r.GET("/orders/:id", func(c *gin.Context) {
		var order model.Order
		if err := config.DB.Preload("Items").First(&order, c.Param("id")).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "订单不存在"})
			return
		}
		c.JSON(http.StatusOK, order)
	})

	// 更新订单状态
	r.PUT("/orders/:id/status", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		var req struct {
			Status string `json:"status"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		if err := s.UpdateOrderStatus(uint(id64), req.Status); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "订单状态更新成功"})
	})

	// 更新支付状态
	r.PUT("/orders/:id/payment", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		var req struct {
			PaymentStatus string `json:"payment_status"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		if err := s.UpdatePaymentStatus(uint(id64), req.PaymentStatus); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "支付状态更新成功"})
	})

	// 生成送货单
	r.POST("/orders/:id/delivery", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		var req struct {
			DeliveryDate    string  `json:"delivery_date"`
			DeliveryAddress string  `json:"delivery_address"`
			DeliveryContact string  `json:"delivery_contact"`
			DeliveryPhone   string  `json:"delivery_phone"`
			Warehouse       string  `json:"warehouse"`
			Packager        string  `json:"packager"`
			Shipper         string  `json:"shipper"`
			ShippingMethod  string  `json:"shipping_method"`
			Freight         float64 `json:"freight"`
			TaxRate         float64 `json:"tax_rate"`
			Discount        float64 `json:"discount"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		if err := s.GenerateDeliveryNote(uint(id64), req); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "送货单生成成功"})
	})

	// 打印送货单
	r.GET("/orders/:id/print", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		deliveryNote, err := s.GetDeliveryNote(uint(id64))
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, deliveryNote)
	})

	// 确认出库
	r.PUT("/orders/:id/outbound", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		var req struct {
			OutboundDate string `json:"outbound_date"`
			Operator     string `json:"operator"`
			Notes        string `json:"notes"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		if err := s.ConfirmOutbound(uint(id64), req); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "出库确认成功"})
	})

	// 确认发货
	r.PUT("/orders/:id/ship", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		var req struct {
			ShipDate   string `json:"ship_date"`
			TrackingNo string `json:"tracking_no"`
			Carrier    string `json:"carrier"`
			Shipper    string `json:"shipper"`
			Notes      string `json:"notes"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		if err := s.ConfirmShipment(uint(id64), req); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "发货确认成功"})
	})

	// 删除订单
	r.DELETE("/orders/:id", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		if err := s.DeleteOrder(uint(id64)); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.Status(http.StatusNoContent)
	})

	// 获取订单统计
	r.GET("/orders/stats", func(c *gin.Context) {
		stats, err := s.GetOrderStats()
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, stats)
	})

	// 获取待出库订单
	r.GET("/orders/outbound/pending", func(c *gin.Context) {
		p := util.GetPage(c)
		var list []model.Order
		q := config.DB.Model(&model.Order{}).Where("status = ?", "待发货")
		var total int64
		q.Count(&total)
		if err := q.Preload("Items").Offset(p.Offset).Limit(p.Limit).Order("id ASC").Find(&list).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"items": list, "total": total, "page": p.Page, "pageSize": p.PageSize})
	})

	// 获取待发货订单
	r.GET("/orders/shipment/pending", func(c *gin.Context) {
		p := util.GetPage(c)
		var list []model.Order
		q := config.DB.Model(&model.Order{}).Where("status = ?", "待发货")
		var total int64
		q.Count(&total)
		if err := q.Preload("Items").Offset(p.Offset).Limit(p.Limit).Order("id ASC").Find(&list).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"items": list, "total": total, "page": p.Page, "pageSize": p.PageSize})
	})

	// 批量更新订单状态
	r.PUT("/orders/batch/status", func(c *gin.Context) {
		var req struct {
			OrderIDs []uint `json:"order_ids"`
			Status   string `json:"status"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		if err := s.BatchUpdateOrderStatus(req.OrderIDs, req.Status); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "批量更新成功"})
	})
}
